<template>
    <div class="resource-usage">
        <div class="header page-title">
            <div class="title-container">
                <h1 class="title">用能计划</h1>
            </div>
            <div class="actions">
                <el-date-picker v-model="selectedYear" style="width: 8rem;
                margin-right: var(--gap-normal);" type="year" placeholder="选择年份" format="YYYY" value-format="YYYY"
                    size="small" @change="handleYearChange" />

                <el-radio-group v-model="planV2Store.activeTab" size="small" @change="planV2Store.setActiveTab"
                    style="margin-right: var(--gap-normal);">
                    <el-radio-button value="water" label="water">用水量</el-radio-button>
                    <el-radio-button value="electricity" label="electricity">用电量</el-radio-button>
                    <el-radio-button value="gas" label="gas">用气量</el-radio-button>
                </el-radio-group>

                <el-button class="refresh-btn" size="small" type="primary" :icon="Refresh" @click="refreshData"
                    :loading="refreshing">刷新数据</el-button>
            </div>
        </div>

        <div class="cards">
            <!-- 月度计划卡片 -->
            <el-card style="height: 50%;display: flex;flex-direction: column;" body-style="flex: 1;" class="usage-card"
                v-loading="planV2Store.loading">
                <template #header>
                    <span class="card-title">
                        月度{{ resourceTypeText }}计划 ({{ planV2Store.filteredMonthlyData.length }}条)
                    </span>
                    <div v-permission="'manage_plan'" class="header-actions">
                        <el-button @click="openAddPlanDialog('month')" type="primary" size="small">
                            编辑计划
                        </el-button>
                    </div>
                </template>
                <div class="chart-container">
                    <PlanChart v-if="planV2Store.filteredMonthlyData.length > 0" type="month"
                        :data="planV2Store.filteredMonthlyData" :metric="planV2Store.activeTab"
                        :year="planV2Store.currentYear" ref="monthChartRef" />
                    <div v-else class="empty-state">
                        <el-empty description="暂无计划数据"></el-empty>
                    </div>
                </div>
            </el-card>

            <div style="height: 50%;" class="cards-row">
                <!-- 季度计划卡片 -->
                <el-card style="height: 100%;display: flex;flex-direction: column;" body-style="flex: 1;"
                    class="usage-card" v-loading="planV2Store.loading">
                    <template #header>
                        <span class="card-title">
                            季度{{ resourceTypeText }}计划 ({{ planV2Store.filteredQuarterlyData.length }}条)
                        </span>
                        <div v-permission="'manage_plan'" class="header-actions">
                            <el-button @click="openAddPlanDialog('quarter')" type="primary" size="small">
                                编辑计划
                            </el-button>
                        </div>
                    </template>
                    <div class="chart-container">
                        <PlanChart v-if="planV2Store.filteredQuarterlyData.length > 0" type="quarter"
                            :data="planV2Store.filteredQuarterlyData" :metric="planV2Store.activeTab"
                            :year="planV2Store.currentYear" ref="quarterChartRef" />
                        <div v-else class="empty-state">
                            <el-empty description="暂无计划数据"></el-empty>
                        </div>
                    </div>
                </el-card>

                <!-- 年度计划卡片 -->
                <el-card style="height: 100%;display: flex;flex-direction: column;" body-style="flex: 1;"
                    class="usage-card" v-loading="planV2Store.loading">
                    <template #header>
                        <span class="card-title">
                            年度{{ resourceTypeText }}计划 ({{ planV2Store.filteredYearlyData.length }}条)
                        </span>
                        <div v-permission="'manage_plan'" class="header-actions">
                            <el-button @click="openAddPlanDialog('year')" type="primary" size="small">
                                编辑计划
                            </el-button>
                        </div>
                    </template>
                    <div class="chart-container">
                        <PlanChart v-if="planV2Store.filteredYearlyData.length > 0" type="year"
                            :data="planV2Store.filteredYearlyData" :metric="planV2Store.activeTab"
                            :year="planV2Store.currentYear" ref="yearChartRef" />
                        <div v-else class="empty-state">
                            <el-empty description="暂无计划数据"></el-empty>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>
    </div>

    <add-resource-plan-dialog ref="addPlanDialogRef" @refresh="handleRefresh"></add-resource-plan-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import { useCompanyStore } from '@/stores/company';
import { usePlanV2Store } from '@/stores/planV2';
import AddResourcePlanDialog from './components/AddResourcePlanDialog.vue';
import { Refresh } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { handleError } from '@/utils/handleError';
// 获取store实例
const companyStore = useCompanyStore();
const planV2Store = usePlanV2Store();

// 本地年份状态，用于处理清空年份的情况
const selectedYear = ref(planV2Store.currentYear);

// 年份变更处理函数
const handleYearChange = (val) => {
    if (val) {
        // 只有当选择了具体年份时才更新store中的年份并请求数据
        planV2Store.setCurrentYear(val);
        if (companyStore.currentCompany?.id) {
            planV2Store.fetchPlanData(companyStore.currentCompany.id);
        }
    } else {
        // 如果清空了年份选择，则恢复为当前年份
        selectedYear.value = dayjs().format('YYYY');
        planV2Store.setCurrentYear(selectedYear.value);
    }
};

// 对话框引用
const addPlanDialogRef = ref(null);

// 图表引用
const monthChartRef = ref(null);
const quarterChartRef = ref(null);
const yearChartRef = ref(null);

// 刷新状态
const refreshing = ref(false);

// 资源类型文本
const resourceTypeText = computed(() => {
    switch (planV2Store.activeTab) {
        case 'water': return '用水';
        case 'electricity': return '用电';
        case 'gas': return '用气';
        default: return '用水';
    }
});

// 打开编辑计划对话框
const openAddPlanDialog = (planType) => {
    const metricType = planV2Store.currentPlanTypeId;
    // 将当前选择的年份传递给对话框组件
    addPlanDialogRef.value?.openDialog(planType, metricType, planV2Store.currentYear);
};

// 刷新数据处理函数
const handleRefresh = async () => {
    if (companyStore.currentCompany?.id) {
        await planV2Store.fetchPlanData(companyStore.currentCompany.id);
    } else {
        ElMessage.error('未选择公司，无法刷新数据');
    }
};

// 刷新按钮点击事件处理
const refreshData = async () => {
    if (!companyStore.currentCompany?.id) {
        ElMessage.error('未选择公司，无法刷新数据');
        return;
    }

    try {
        refreshing.value = true;

        // 刷新计划数据
        await planV2Store.fetchPlanData(companyStore.currentCompany.id);

        // 刷新各图表的实际数据
        if (monthChartRef.value && monthChartRef.value.fetchActualData) {
            await monthChartRef.value.fetchActualData();
        }

        if (quarterChartRef.value && quarterChartRef.value.fetchActualData) {
            await quarterChartRef.value.fetchActualData();
        }

        if (yearChartRef.value && yearChartRef.value.fetchActualData) {
            await yearChartRef.value.fetchActualData();
        }

        ElMessage.success('数据刷新成功');
    } catch (error) {
        handleError(error, '刷新数据失败');
    } finally {
        refreshing.value = false;
    }
};

// 监听公司变化，并立即执行一次
watch(() => companyStore.currentCompany, (newCompany) => {
    if (newCompany && newCompany.id) {
        planV2Store.fetchPlanData(newCompany.id);
    }
}, { immediate: true });

// 监听store中currentYear的变化，同步到本地selectedYear
watch(() => planV2Store.currentYear, (newYear) => {
    selectedYear.value = newYear;
}, { immediate: true });
</script>

<style lang="scss" scoped>
.resource-usage {
    display: flex;
    flex-direction: column;
    height: 100%;

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .actions {
            display: flex;
            align-items: center;
        }

        .title-container {
            display: flex;
            align-items: center;
            gap: 16px;

            .title {
                font-size: 20px;
                font-weight: 600;
                color: #1f2937;
                margin: 0;
            }
        }
    }

    .cards {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 16px;
        margin-bottom: 20px;


        .chart-container {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .empty-state {
            height: 100%;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .cards-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .header-actions {
            display: flex;
            align-items: center;
        }
    }
}

@media (max-width: 1400px) {
    .resource-usage {
        .cards-row {
            min-height: 600px;
            grid-template-columns: 1fr !important;
        }
    }
}

// 移动端
@media (max-width: 768px) {
    .title {
        display: none
    }

    .refresh-btn {
        display: none;
    }

}
</style>